import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {Popconfirm, Table, Button, Form, Row, Col, Card, Spin, Modal} from 'antd';
import {getDetail} from './api';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH, FORM_ROW_OPTIONS, DATETIME_FORMAT} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {conventEnumValueToString, formatAmount, formatPercent, formatDateTime} from '../utils';
import {PERMISSION, packing} from './constants';
import {newOrUpdateOrderValidator, approveValidator} from './validator';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import InputAmount from '../common/InputAmount';
import SearchInput from 'Shared/components/SearchInput';
import LetterOfCreditSelectPanel from './LetterOfCreditSelectPanel';
import SaleOrderPanel from './SaleOrderPanel';
import SaleOrderDetailPanel from './SaleOrderDetailPanel';
import {currency, saleOrderPriceTerms, paymentType, saleOrderTransportType, saleOrderType, packingWay, saleOrderResultJudgeResult} from '../Enum';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
const {Description} = DescriptionList;
const basePath = fetch.basePath || '';
const url = '/#/dcs/sales/letterOfCredit';
const packingWayList = packing.toList(language);
const paymentTypeList = paymentType.toList(language);
const transportTypeList = saleOrderTransportType.toList(language);

export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        valiSaleOrder: false,
        data: {},
        details: [],
        showLetterOfCreditPanel: false,
        showSaleOrderPanel: false,
        showSaleOrderDetailPanel: false,
        saleProformaInvoices: [],
        saleConfirmationResults: []
    };

    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id) {
            this.setState(({
                loading: true
            }));
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details,
                            saleConfirmationResults: res.data.saleConfirmationResults,
                            saleProformaInvoices: res.data.saleProformaInvoices ? res.data.saleProformaInvoices.map(item => ({
                                text: item.code,
                                value: item.id,
                                shipmentAmount: item.shipmentAmount,
                                insuranceAmount: item.insuranceAmount,
                            })) : [],
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    priceOnChange = (price, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    price,
                    totalPrice: price * d.quantity
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    OnChangeinsidePrice = (insidePrice, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    insidePrice,
                    insideTotalPrice: insidePrice * d.quantity
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    handleFilterChange = (value, name) => {
        if(name === 'saleProformaInvoiceId') {
            const saleProformaInvoice = this.state.saleProformaInvoices.find(v => v.value === value);
            const data = Object.assign({}, this.state.data, {
                [name]: value,
                shipmentAmount: this.state.data.salesOrderPriceTerms === saleOrderPriceTerms.CIF ||
                this.state.data.salesOrderPriceTerms === saleOrderPriceTerms.CPT ||
                this.state.data.salesOrderPriceTerms === saleOrderPriceTerms.CIP ||
                this.state.data.salesOrderPriceTerms === saleOrderPriceTerms.CFR ? saleProformaInvoice.shipmentAmount : 0,
                insuranceAmount: this.state.data.salesOrderPriceTerms === saleOrderPriceTerms.CIF ||
                this.state.data.salesOrderPriceTerms === saleOrderPriceTerms.CIP ? saleProformaInvoice.insuranceAmount : 0,
            });
            this.setState({
                data,
                hasOperat: true
            });
        } else {
            const data = Object.assign({}, this.state.data, {
                [name]: value
            });
            this.setState({
                data,
                hasOperat: true
            });
        }
    }
    onChangeQuantity = (quantity, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    quantity,
                    totalPrice: d.price * quantity,
                    insideTotalPrice: d.insidePrice * quantity
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onChangeBrand = (value, name) => {
        if(this.state.data.brandId !== undefined && this.state.data.brandId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switchBrandId',
                    defaultMessage: '变更品牌，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitch(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                }),
                hasOperat: true
            });
    }
    onChangeSwitch = (value, name) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    dealerId: newData.dealerId,
                    dealerCode: newData.dealerCode,
                    dealerName: newData.dealerName,
                    [name]: value,
                },
                details: []
            };
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const isValid = newOrUpdateOrderValidator(this.state.data, this.state.details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data, this.state.details).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    
    onSubmitPass = () => {
        const isValid = approveValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmitPass(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    
    onSubmitReject = () => {
        const isValid = approveValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmitReject(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSelectDealer = (condition = {}) => {
        if(this.state.data.dealerId !== undefined && this.state.data.dealerId !== condition.id)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switchDealerId',
                    defaultMessage: '变更总代，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchDealer(condition)
            });
        else
            this.setState(state => {
                const newData = cloneDeep(state.data);
                return {
                    hasOperat: true,
                    data: {
                        ...newData,
                        dealerId: condition.id,
                        dealerCode: condition.code,
                        dealerName: condition.name,
                        marketDepartmentName: condition.marketDepartmentName,
                        country: condition.countryName,
                    }
                };
            });
    };
    onChangeSwitchDealer = condition => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    brandId: newData.brandId,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                },
                details: []
            };
        });
    }
    onClickLetterOfCreditSearchBtn = () => {
        this.setState({showLetterOfCreditPanel: true});
    }
    onCloseLetterOfCreditSelectPanel = () => {
        this.setState({showLetterOfCreditPanel: false});
    }
    onSelectAddedLetterOfCredit = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                letterOfCreditId: records.id,
                letterOfCreditCode: records.lcCode,
                lcVersionCode: records.versionCode,
                orderPrice: records.orderPrice,
                cashInPrice: records.cashInPrice,
            }),
            hasOperat: true,
            showLetterOfCreditPanel: false
        });
    }
    onClickAddSaleOrderBtn = () => {
        this.setState({showSaleOrderPanel: true});
    }
    onCloseSaleOrderPanel = () => {
        this.setState({showSaleOrderPanel: false});
    }
    onSelectSaleOrder = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                saleOrderId: records.id,
                salesOrderCode: records.code,
                orderType: records.orderType,
                currency: records.currency,
                tradeMethodId: records.tradeMethodId,
                tradeMethodName: records.tradeMethodName,
                payment: records.paymentType,
                salesOrderPriceTerms: records.salesOrderPriceTerms,
                taxRate: records.taxRate,
                transportType: records.transportType,
                carrierId: records.carrierId,
                carrierName: records.carrierName,
                shippingPortId: records.shippingPortId,
                shippingPortName: records.shippingPortName,
                destinationPort: records.destinationPort,
                batchNumber: records.batchNumber,
            }),
            saleProformaInvoices: records.saleProformaInvoices ? records.saleProformaInvoices.map(item => ({
                text: item.code,
                value: item.id,
                shipmentAmount: item.shipmentAmount,
                insuranceAmount: item.insuranceAmount,
            })) : [],
            details: this.state.data.saleOrderId === records.id ? this.state.data.details : [],
            hasOperat: true,
            showSaleOrderPanel: false,
            showSaleOrderDetailPanel: true
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true,
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== id);
        if(this.state.details.length !== 0)
            this.setState({
                details: [...tmp],
                hasOperat: true,
            });
        if(this.state.details.length === 0)
            this.setState({
                data: {dataSource: undefined}
            });
    }
    onRemarkChange = (remark, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    remark,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onProBatchNumberChange = (proBatchNumber, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    proBatchNumber,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onClickAddSaleOrderDetailBtn = () => {
        this.setState({showSaleOrderDetailPanel: true});
    }
    onSelectAddedSaleOrderDetail = records => {
        const retailDetails = this.state.details || [];
        records.forEach(r => {
            const index = retailDetails.findIndex(v => v.saleOrderId === r.id);
            if(index === -1)
                retailDetails.push({
                    id: r.id,
                    salesOrderDetailId: r.id,
                    productCode: r.productCode,
                    productName: r.productName,
                    productGroupCode: r.productGroupCode,
                    productGroupName: r.productGroupName,
                    descriptionOfGoods: r.productGroupCode,
                    quantity: r.quantity,
                    price: r.price,
                    totalPrice: r.totalPrice,
                    productCategoryCode: r.productCategoryCode,
                    productCategoryName: r.productCategoryName
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showSaleOrderDetailPanel: false
        });
    }
    onCloseSaleOrderDetailPanel = () => {
        if(this.state.details.length <= 0)
            this.setState({data: Object.assign({}, this.state.data, {
                saleOrderId: '',
                salesOrderCode: '',
                orderType: '',
                currency: '',
                tradeMethodId: '',
                tradeMethodName: '',
                payment: '',
                salesOrderPriceTerms: '',
                taxRate: '',
                transportType: '',
                carrierId: '',
                shippingPortId: '',
                carrierName: '',
                shippingPortName: '',
                destinationPort: '',
                batchNumber: '',
                letterOfCreditId: '',
                letterOfCreditCode: '',
                lcVersionCode: '',
                orderPrice: '',
                cashInPrice: '',
            })});
        this.setState({showSaleOrderDetailPanel: false});
    }
    render() {
        const {data, details = [], saleProformaInvoices, saleConfirmationResults} = this.state;
        const {page, initEnum} = this.props;
        if(initEnum.brands.length === 1 && !this.props.id) {
            data.brandId = initEnum.brands[0].value;
            data.brandName = initEnum.brands[0].text;
        }
        const carriersList = initEnum.carriers.filter(v => v.brandId === data.brandId);
        const shippingPortsList = initEnum.shippingPorts.filter(v => v.brandId === data.brandId);
        const currentSelectRowkeys = details.map(item => item.salesOrderDetailId);
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        let productAmount = 0;
        let totalAmount = 0;
        let totalQuantity = 0;
        let insideTotalAmount = 0;
        details.forEach(o => {
            productAmount += o.totalPrice;
            totalQuantity += o.quantity;
            insideTotalAmount += o.insideTotalPrice || 0;
        });
        totalAmount = productAmount + (data.shipmentAmount || 0) + (data.insuranceAmount || 0) + (data.otherAmount || 0);
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateSalesOrder = !data.saleOrderId && this.state.validate ? 'error' : null;
        const validateBatchNumber = !data.batchNumber && this.state.validate ? 'error' : null;
        const validateApproveComment = !data.approveComment && this.state.validate ? 'error' : null;
        const validateLetterOfCreditId = (data.payment === paymentType['L/C'] && !data.letterOfCreditId) && this.state.validate ? 'error' : null;
        const validateTransportType = !data.transportType && this.state.validate ? 'error' : null;
        const validateShippingPortId = !data.shippingPortId && this.state.validate ? 'error' : null;
        const validateDestinationPort = !data.destinationPort && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        const columns = [{
            title: formatMessage({
                id: 'newPanel.column.productCode',
                defaultMessage: '物料号'
            }),
            dataIndex: 'productCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.productName',
                defaultMessage: '物料名称'
            }),
            dataIndex: 'productName'
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
            width: 100,
            render: (text, record) => {
                const validate = (!text || text === undefined || text === 0) ? {validateStatus: 'error'} : null;
                return this.props.page === 'approve' ? formatAmount(text) : (<FormItem {...validate}>
                    <LocalizeInputNumber
                        id={record.id}
                        min={1}
                        precision={0}
                        value={record.quantity}
                        onChange={this.onChangeQuantity}/>
                </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            width: 150,
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                return this.props.page === 'approve' ? formatAmount(text) : (<FormItem {...validate}>
                    <InputAmount
                        id={record.id}
                        min={0}
                        value={record.price}
                        onChange={this.priceOnChange}/>
                </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.totalPrice',
                defaultMessage: '总价'
            }),
            dataIndex: 'totalPrice',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.productGroupCode',
                defaultMessage: '物料组编号'
            }),
            dataIndex: 'productGroupCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.productGroupName',
                defaultMessage: '物料组名称'
            }),
            dataIndex: 'productGroupName'
        }, {
            title: formatMessage({
                id: 'newPanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.productCategoryName',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'productCategoryName'
        },
        //  {
        //     title: formatMessage({
        //         id: 'newPanel.column.insidePrice',
        //         defaultMessage: '内销价'
        //     }),
        //     dataIndex: 'insidePrice',
        //     render: (text, record) => {
        //         const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
        //         return this.props.page === 'approve' ? formatAmount(text) : (<FormItem {...validate}>
        //             <InputAmount
        //                 id={record.id}
        //                 min={0}
        //                 value={record.insidePrice}
        //                 onChange={this.OnChangeinsidePrice}/>
        //         </FormItem>
        //         );
        //     }
        // }, {
        //     title: formatMessage({
        //         id: 'newPanel.column.insideTotalPrice',
        //         defaultMessage: '内销总价'
        //     }),
        //     dataIndex: 'insideTotalPrice',
        //     render: text => formatAmount(text)
        // }, 
        {
            title: formatMessage({
                id: 'newPanel.column.proBatchNumber',
                defaultMessage: '生产批次号'
            }),
            dataIndex: 'proBatchNumber',
            render: (text, record) =>
                this.props.page === 'approve' ? text : (<FormItem>
                    <TextInput
                        id={record.id}
                        min={0}
                        value={text}
                        onChange={this.onProBatchNumberChange}/>
                </FormItem>
                )
        }, {
            title: formatMessage({
                id: 'newPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
            render: (text, record) =>
                this.props.page === 'approve' ? text : (<FormItem>
                    <TextInput
                        id={record.id}
                        min={0}
                        value={text}
                        onChange={this.onRemarkChange}/>
                </FormItem>
                )
        }];
        if(this.props.page !== 'approve')
            columns.push({
                title: details.length > 0
                    ? (
                        <Popconfirm placement="topRight" title={formatMessage({
                            id: 'newPanel.validation.isDelete',
                            defaultMessage: '是否确认全部删除？'
                        })} onConfirm={this.onDeleteAll} >
                            <a>{formatMessage({
                                id: 'newPanel.validation.clear',
                                defaultMessage: '清空'
                            })}</a>
                        </Popconfirm>
                    )
                    : null,
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                    id: 'newPanel.validation.delete',
                    defaultMessage: '删除'
                })}</a>
            });
        const columnResults = [{
            title: formatMessage({
                id: 'newPanel.column.approverCode',
                defaultMessage: '审核人编号'
            }),
            dataIndex: 'approverCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment',
            render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            render: text => conventEnumValueToString(saleOrderResultJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation'
        }];
        const salesOrderComp = (data.brandId && data.dealerId)
            ? (<SearchInput
                disabled={true}
                value={data.salesOrderCode}
                id={data.saleOrderId}
                onClickSearchBtn={this.onClickAddSaleOrderBtn} />) : (<TextInput name="salesOrderCode"
                value={''} disabled placeholder={this.props.intl.formatMessage({
                    id: 'newPanel.dealerComp.brandAndDealer',
                    defaultMessage: '请先选择品牌和总代'
                })} />);
        // eslint-disable-next-line no-nested-ternary
        const letterOfCreditComp = data.saleOrderId
            ? (data.payment === paymentType['L/C'] ? <SearchInput
                disabled={true}
                value={data.letterOfCreditCode}
                id={data.letterOfCreditId}
                onClickSearchBtn={this.onClickLetterOfCreditSearchBtn} /> : <TextInput name="letterOfCreditId"
                value={''} disabled />) : (<TextInput name="letterOfCreditId"
                value={''} disabled placeholder={this.props.intl.formatMessage({
                    id: 'newPanel.dealerComp.saleOrderId',
                    defaultMessage: '请先选择销售订单'
                })} />);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.code || '尚未生成'}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                {this.props.initEnum.brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required>
                                        {data.id ? `(${data.brandCode})${data.brandName}` : <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={this.props.initEnum.brands}
                                            onChange={this.onChangeBrand}/>}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                        {data.id ? `(${data.dealerCode})${data.dealerName}` : <DealerSelectPanel
                                            value={dealerInfo}
                                            onChange={this.handleFilterChange}
                                            onSelect={this.onSelectDealer} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.marketDepartmentName',
                                            defaultMessage: '大区'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.marketDepartmentName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.country',
                                            defaultMessage: '国家'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.salesOrderCode',
                                            defaultMessage: '销售订单编号'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateSalesOrder} required>
                                        {data.id ? data.salesOrderCode : salesOrderComp}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.letterOfCredit',
                                            defaultMessage: '信用证号'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateLetterOfCreditId}
                                        required={page !== 'approve' && data.payment === paymentType['L/C']}>
                                        {page === 'approve'
                                            ? <a href={`${basePath}${url}/${data.letterOfCreditId}/detail`}
                                                target="_blank" rel="noopener noreferrer">{data.letterOfCreditCode}</a>
                                            : letterOfCreditComp}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.saleProformaInvoice',
                                        defaultMessage: 'PI形式发票'
                                    })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? data.saleProformaInvoiceCode : <WrappedSelect
                                            allowClear
                                            name="saleProformaInvoiceId"
                                            value={data.saleProformaInvoiceId}
                                            options={saleProformaInvoices}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.packingWay',
                                            defaultMessage: '包装方式'
                                        })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? conventEnumValueToString(packingWay, data.packingWay) : <WrappedSelect
                                            allowClear
                                            name="packingWay"
                                            value={data.packingWay}
                                            options={packingWayList}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.batchNumber',
                                            defaultMessage: '批次号'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBatchNumber} required>
                                        {page === 'approve' ? data.batchNumber : <TextInput
                                            name="batchNumber"
                                            value={data.batchNumber}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.marks',
                                            defaultMessage: '标记'
                                        })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? data.marks : <TextInput
                                            name="marks"
                                            value={data.marks}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.insurance',
                                            defaultMessage: '保险'
                                        })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? data.insurance : <TextInput
                                            name="insurance"
                                            value={data.insurance}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                {data.saleOrderId && (data.salesOrderPriceTerms === saleOrderPriceTerms.CIF ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CPT ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CIP ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CFR) && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.shipmentAmount',
                                        defaultMessage: '运费'
                                    })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? formatAmount(data.shipmentAmount) : <InputAmount
                                            name="shipmentAmount"
                                            value={data.shipmentAmount}
                                            onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                }
                                {data.saleOrderId && (data.salesOrderPriceTerms === saleOrderPriceTerms.CIF ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CIP) && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.insuranceAmount',
                                        defaultMessage: '保费'
                                    })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? formatAmount(data.insuranceAmount) : <InputAmount
                                            name="insuranceAmount"
                                            value={data.insuranceAmount}
                                            onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.otherAmount',
                                        defaultMessage: '其他费用'
                                    })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? formatAmount(data.otherAmount) : <InputAmount
                                            name="otherAmount"
                                            value={data.otherAmount}
                                            onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.paymentType',
                                        defaultMessage: '付款方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? conventEnumValueToString(paymentType, data.payment) : <WrappedSelect
                                            allowClear
                                            name="payment"
                                            value={data.payment}
                                            options={paymentTypeList}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.transportType',
                                            defaultMessage: '运输方式'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateTransportType} required>
                                        {page === 'approve' ? conventEnumValueToString(saleOrderTransportType, data.transportType) : <WrappedSelect
                                            allowClear
                                            name="transportType"
                                            value={data.transportType}
                                            options={transportTypeList}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.carrierName',
                                            defaultMessage: '指定货代'
                                        })} {...FORM_OPTIONS.item}>
                                        {page === 'approve' ? data.carrierName : <WrappedSelect
                                            allowClear
                                            name="carrierId"
                                            value={data.carrierId}
                                            options={carriersList}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.shippingPortName',
                                            defaultMessage: '发运港口'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateShippingPortId} required>
                                        {page === 'approve' ? data.shippingPortName : <WrappedSelect
                                            allowClear
                                            name="shippingPortId"
                                            value={data.shippingPortId}
                                            options={shippingPortsList}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.destinationPort',
                                            defaultMessage: '目的港口'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateDestinationPort} required>
                                        {page === 'approve' ? data.destinationPort : <TextInput
                                            name="destinationPort"
                                            value={data.destinationPort}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.LCVersionCode',
                                            defaultMessage: '信用证版本号'
                                        })} {...FORM_OPTIONS.item}>
                                        {data.lcVersionCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.orderType',
                                            defaultMessage: '订单类型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(saleOrderType, data.orderType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.currency',
                                            defaultMessage: '币种'
                                        })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.tradeMethod',
                                            defaultMessage: '贸易方式'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.tradeMethodName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.salesOrderPriceTerms',
                                        defaultMessage: '价格条款'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(saleOrderPriceTerms, data.salesOrderPriceTerms)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.taxRate',
                                            defaultMessage: '税率'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatPercent(data.taxRate)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.orderPrice',
                                            defaultMessage: '信用证总额'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(data.orderPrice)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.cashInPrice',
                                            defaultMessage: '信用证余额'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(data.cashInPrice)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.productAmount',
                                            defaultMessage: '清单总额'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(productAmount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.totalAmount',
                                            defaultMessage: '总金额'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(totalAmount)}
                                    </FormItem>
                                </Col>
                                {/* <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.insideTotalAmount',
                                            defaultMessage: '内销总金额'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(insideTotalAmount || 0)}
                                    </FormItem>
                                </Col> */}
                            </Row>
                            <Row>
                                <Col {...FORM_ROW_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'newPanel.details',
                                defaultMessage: '清单'
                            })}
                            extra={page !== 'approve' && <div>
                                <Button
                                    disabled={!data.saleOrderId}
                                    size="small"
                                    onClick={this.onClickAddSaleOrderDetailBtn}>
                                    {formatMessage({
                                        id: 'newPanel.operation.newSaleOrderDetail',
                                        defaultMessage: '新增清单'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="salesOrderDetailId"
                                pagination={false}
                                dataSource={details}
                                footer={() => (<DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalQuantity',
                                        defaultMessage: '总数量'
                                    })}>{totalQuantity ? totalQuantity : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalAmount',
                                        defaultMessage: '总金额'
                                    })}>{formatAmount(totalAmount ? totalAmount : null)}
                                    </Description>
                                    {/* <Description term={formatMessage({
                                        id: 'detailPanel.operation.insideTotalAmount',
                                        defaultMessage: '内销总金额'
                                    })}>{formatAmount(insideTotalAmount ? insideTotalAmount : null)}
                                    </Description> */}
                                </DescriptionList>)}
                                {...TABLE} />
                        </Card>
                        {page === 'approve' && <Card
                            title={formatMessage({
                                id: 'newPanel.saleConfirmationResults',
                                defaultMessage: '审核结果清单'
                            })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columnResults}
                                rowKey="id"
                                pagination={false}
                                dataSource={saleConfirmationResults}
                                {...TABLE} />
                        </Card>}
                        {page === 'approve' && <Card
                            title={formatMessage({
                                id: 'newPanel.approve',
                                defaultMessage: '审核区域'
                            })}>
                            <Row>
                                <Col {...FORM_ROW_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.approveComment',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateApproveComment} required>
                                        <TextInput type="textarea"
                                            name="approveComment"
                                            value={data.approveComment}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>}
                        <Card type="inner">
                            <Row>
                                {
                                    page !== 'approve' && <Col disabled={!submitable} className="col-align-right">
                                        <Button key="submit" loading={this.state.loading}
                                            onClick={this.onSubmit} type="primary">{formatMessage({
                                                id: 'newPanel.btn.submit',
                                                defaultMessage: '保存'
                                            })}</Button>
                                    </Col>
                                }
                                {
                                    page === 'approve' && <Col disabled={!submitable} className="col-align-right">
                                        {data.nextApproveNumber < 4 && <Button key="submitPass" loading={this.state.loading}
                                            onClick={this.onSubmitReject}>{formatMessage({
                                                id: 'newPanel.btn.submitPass',
                                                defaultMessage: '驳回'
                                            })}</Button>}
                                        <Button key="submitReject" loading={this.state.loading}
                                            onClick={this.onSubmitPass} type="primary">{formatMessage({
                                                id: 'newPanel.btn.submitReject',
                                                defaultMessage: '审核通过'
                                            })}</Button>
                                    </Col>
                                }
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
                {
                    this.state.showLetterOfCreditPanel &&
                        <LetterOfCreditSelectPanel
                            selectKey={data.id}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            currency={data.currency}
                            onCancel={this.onCloseLetterOfCreditSelectPanel}
                            onSelect={this.onSelectAddedLetterOfCredit} />
                }
                {
                    this.state.showSaleOrderPanel &&
                        <SaleOrderPanel
                            selectKey={data.id}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            onCancel={this.onCloseSaleOrderPanel}
                            onSelect={this.onSelectSaleOrder} />
                }
                {
                    this.state.showSaleOrderDetailPanel &&
                        <SaleOrderDetailPanel
                            currentSelectRowkeys={currentSelectRowkeys}
                            selectKey={data.id}
                            saleOrderId={data.saleOrderId}
                            onCancel={this.onCloseSaleOrderDetailPanel}
                            onSelect={this.onSelectAddedSaleOrderDetail} />
                }
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onSubmitPass: PropTypes.func.isRequired,
    onSubmitReject: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    page: PropTypes.string,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onNewUpdate,
    tableSearch,
    onApprove,
    onReject
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const tradeMethods = initData.tradeMethods ? initData.tradeMethods.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const carriers = initData.carriers ? initData.carriers.map(item => ({
            text: item.name,
            value: item.id,
            brandId: item.brandId
        })) : [];
        const shippingPorts = initData.shippingPorts ? initData.shippingPorts.map(item => ({
            text: item.name,
            value: item.id,
            brandId: item.brandId
        })) : [];
        return {
            brands,
            tradeMethods,
            carriers,
            shippingPorts
        };
    }
);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: (data, details) => dispatch(onNewUpdate(data, details)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onSubmitPass: (data, details) => dispatch(onApprove(data, details)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onSubmitReject: (data, details) => dispatch(onReject(data, details)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
